package cn.tedu.store.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.tedu.store.bean.Goods;
import cn.tedu.store.bean.GoodsCategory;
import cn.tedu.store.bean.ResponseResult;
import cn.tedu.store.service.IGoodsCategoryService;
import cn.tedu.store.service.IGoodsService;

@RequestMapping("/main")
@Controller
public class MainController extends BaseController{
	@Resource(name="goodsCategoryService")
	private IGoodsCategoryService goodsCategoryService;
	@Resource(name="goodsService")
	private IGoodsService goodsService;
	
	@RequestMapping(value="/index.do")
	public String showIndex(ModelMap modelMap) {
		//声明电脑的分类
		List<List<GoodsCategory>> computerList =new ArrayList<List<GoodsCategory>>();
		//声明电脑的前三名商品
		List<Goods> computers=new ArrayList<Goods>();
		computers=goodsService.getGoodsListByCategoryId(163, 0, 3);
		//获取161的3个二级分类
		List<GoodsCategory> categories=
				goodsCategoryService.getGoodsCategoryListByParentId(161, 0, 3);
		//computerList.add(categories);
		//获取各2级分类的三级分类
		List<GoodsCategory> subCategories;
		for(GoodsCategory goodsCategory : categories) {
			subCategories=goodsCategoryService.getGoodsCategoryListByParentId(goodsCategory.getId(), null, null);
			computerList.add(subCategories);
		}
		//封装需要发送的数据
		modelMap.addAttribute("computerList", computerList);
		modelMap.addAttribute("categories", categories);
		modelMap.addAttribute("computers", computers);
		return "index";
	}
	@RequestMapping("/check_code.do")
	@ResponseBody
	public ResponseResult<Void> checkCode(String code,HttpSession session){
		String c=(String) session.getAttribute("code");
		ResponseResult<Void> rr;
		if(c==null) {
			return new ResponseResult<Void>(0, "验证失败");
		}
		//忽略大小写的比较
		if(c.equalsIgnoreCase(code)) {
			return new ResponseResult<Void>(1, "验证成功");
		}
		return new ResponseResult<Void>(0, "验证失败");
	}
	
	/**
	 * 生成验证码
	 * @throws IOException 
	 */
	//produces用于设定context-type属性
	@RequestMapping(value="/code.do",produces="image/png")
	//与返回值byte[]配合，填充Response的body部分。
	@ResponseBody
	public byte[] code(HttpSession session) throws IOException {
		String code=createCode(4);
		session.setAttribute("code", code);
		byte[] bytes=createPng(code);
		return bytes;
	}
	private byte[] createPng(String code) throws IOException{
		//创建图片对象
		BufferedImage img=new BufferedImage(100, 40, BufferedImage.TYPE_3BYTE_BGR);
		//img.setRGB(0, 0, 0x0000ff);
		//img.setRGB(50, 20,0xffff00);
		Random r=new Random();
		for(int i=0;i<500;i++) {
			int x=r.nextInt(img.getWidth());
			int y=r.nextInt(img.getHeight());
			int rgb=r.nextInt(0xFFFFFF);
			img.setRGB(x, y, rgb);
		}
		Graphics2D g=img.createGraphics();
		Color c=new Color(r.nextInt(0xFFFFFF));
		g.setColor(c);
		//黑体，斜体，字体的大小
		Font font=new Font(Font.SANS_SERIF,Font.ITALIC,35);
		g.setFont(font);
		g.drawString(code, 5, 36);
		//利用API绘制混淆线
		for(int i=0;i<5;i++) {
			int x1=r.nextInt(img.getWidth());
			int y1=r.nextInt(img.getHeight());
			int x2=r.nextInt(img.getWidth());
			int y2=r.nextInt(img.getHeight());
			g.drawLine(x1, y1, x2, y2);
		}
		//将图片对象编码为png数据
		ByteArrayOutputStream out=new ByteArrayOutputStream();
		ImageIO.write(img, "png", out);
		out.close();
		byte[] bytes=out.toByteArray();
		return bytes;
	}
	private String createCode(int i) {
		String chs="abcdefghijkmnpqxy"
				+ "ABCDEFGHJKLMNPQRSTUV"
				+ "34568";
		char[] code=new char[i];
		Random r=new Random();
		for(int n=0;n<code.length;n++) {
			int index=r.nextInt(chs.length());
			code[n]=chs.charAt(index);
		}
		return new String(code);
	}
	@RequestMapping(value="/download_Png.do",produces="image/png")
	@ResponseBody
	public byte[] downloadPng(HttpServletResponse response)
		throws IOException{
		response.setHeader("Content-Disposition", 
				"attachment; filename=\"demo.png\"");
		byte[] bytes=createPng("Hello"); 
		return bytes;
	}
	/**
	 * excel导出(下载)
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/export.do",
			produces="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
	@ResponseBody
	public byte[] exportExcel(HttpServletResponse response) 
			throws IOException{
		response.setHeader("Content-Disposition", 
				"attachment; filename=\"demo.xlsx\"");
		byte[] bytes=creaeteExcel();
		return bytes;
	}
	private byte[] creaeteExcel() throws IOException{
		//利用POI API 创建工作簿
		XSSFWorkbook workbook=new XSSFWorkbook();
		//在工作簿中创建工作表,参数为工作表名
		XSSFSheet sheet=workbook.createSheet("demo");
		//在工作表创建行，参数为行号
		XSSFRow row=sheet.createRow(0);
		//在行中创建单元格，参数是单元格的序号
		XSSFCell cell=row.createCell(0);
		//在单元格中添加数据
		cell.setCellValue("Hello World");
		//利用ByteArrayOutputStream作为酱油瓶
		ByteArrayOutputStream out=new ByteArrayOutputStream();
		workbook.write(out);
		out.close();
		byte[] bytes=out.toByteArray();
		return bytes;
	}
	@RequestMapping("/upload.do")
	@ResponseBody
	public ResponseResult<Void> upload(MultipartFile images,String memo,HttpServletRequest request) throws  IOException{
		//MultipartFile封装了全部的上传文件的信息
		//显示上载文件的文件名
		String filename=images.getOriginalFilename();
		//String path="D:/files";
		String path="/uploads";
		//将WEB路径转换为当前操作系统的实际路径
		path=request.getServletContext().getRealPath(path);
		File dir=new File(path);
		File file=new File(dir,filename);
		images.transferTo(file);
		return new ResponseResult<Void>(1, "上传成功");
	}
}
